package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecService {

    @Autowired
    private SpecGroupMapper groupMapper;

    @Autowired
    private SpecParamMapper paramMapper;

    public List<SpecGroupDTO> queryGroupByCategory(Long id) {
        SpecGroup s = new SpecGroup();
        s.setCid(id);
        List<SpecGroup> list = groupMapper.select(s);
        if (CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list,SpecGroupDTO.class);
    }

    public List<SpecParamDTO> queryParams(Long gid, Long cid, Boolean searching) {
        SpecParam s = new SpecParam();
        s.setGroupId(gid);
        s.setCid(cid);
        s.setSearching(searching);
        List<SpecParam> list = paramMapper.select(s);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SpecParamDTO.class);
    }

    public List<SpecGroupDTO> querySpecsByCid(Long id) {
        //查询规格组
        List<SpecGroupDTO> groupList = queryGroupByCategory(id);
        //查询分类下所有规格参数
        List<SpecParamDTO> params = queryParams(null, id, null);
        //将规格参数按照groupId进行分组，得到每个group下的params的集合
        Map<Long, List<SpecParamDTO>> paramMap = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //填写到group中
        for (SpecGroupDTO groupDTO : groupList) {
            groupDTO.setParams(paramMap.get(groupDTO.getId()));
        }
        return groupList;
    }
}
